import java.util.Deque;
import java.util.LinkedList;

/**
 * @author VernHe
 * @date 2021年10月28日 11:28
 *
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution_0538 {
    public TreeNode convertBST(TreeNode root) {
        if (null == root) {
            return null;
        }
        // 将二叉搜索树按照顺序放入队列，然后依次弹出并累加
        Deque<TreeNode> queue = new LinkedList<>();
        search(root, queue);
        int sum = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            node.val += sum;
            sum = node.val;
        }
        return root;
    }

    /**
     * 按照中序遍历，将节点放入队列中
     * @param node  节点
     * @param queue 队列
     */
    private void search(TreeNode node, Deque<TreeNode> queue) {
        // 递归基
        if (null == node) {
            return;
        }
        // 中序遍历
        if (null != node.left) {
            search(node.left, queue);
        }
        queue.push(node);
        if (null != node.right) {
            search(node.right, queue);
        }
    }


    /**
     * 优化
     * @param root
     * @return
     */
    public TreeNode convertBST1(TreeNode root) {
        if (null == root) {
            return null;
        }
        Integer sum = 0;
        search1(root, sum);
        return root;
    }

    private int search1(TreeNode node, Integer sum) {
        // 递归基
        if (null == node) {
            return sum;
        }
        // 右子树节点的和
        int rightValue;
        // 反向的中序遍历【右中左】
        if (null != node.right) {
            // 右边有还节点
            rightValue = search1(node.right, sum);
            sum = rightValue;
        } else {
            rightValue = sum;
        }
        node.val = node.val + rightValue;
        sum = node.val;
        if (null != node.left) {
            return search1(node.left, sum);
        } else {
            return sum;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(1);
        root.right = new TreeNode(6);

        new Solution_0538().convertBST1(root);

    }
}
